package com.example.cinema.request;

import android.os.AsyncTask;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class OkhttpBlock implements ProgressResponseListener {
    //视频文件分块
    public byte[] FileDecollate(long start, int chunksize, File file) throws IOException {
        byte[] chunk = new byte[chunksize];//创建分块大小
        RandomAccessFile accessFile = null;
        try {
            accessFile = new RandomAccessFile(file, "r");
            accessFile.seek(start);//移动到文件制定位置
            int i = accessFile.read(chunk);//读取一段直接到制定字节数组中
            if (i == -1) {
                //读取失败
                return null;
            }
            if (i == chunksize) {
                //读取成功;
                return chunk;
            }
            //当剩余的直接不够指定大小时进行以下操作
            byte[] bytes = new byte[i];
            System.arraycopy(chunk, 0, bytes, 0, i);
            return bytes;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (accessFile != null) {
                accessFile.close();
            }
        }
        return null;
    }

    /**
     * 分块上传
     * @param file   文件
     * @param size   文件大小
     * @param id     文件ID（唯一）
     * @param name   文件名
     * @param chunks 分块数量
     * @param chunk  当前分块数
     * @param vname  用户创建标题
     * @param vtext  文件内容
     * @param vtag   文件标签
     * @param usid 用户ID
     * @param  uname 用户名
     * @param url 上传域名
     * @throws IOException
     */
    public void upfile(File file, long size, String id, String name, String chunks, String
            chunk, String vname, String vtext, String vtag,String usid,String uname,String url) throws IOException {
        String filename = file.getName();
        final int chunksize = 1024 * 1024 * 2;
        int cs = Integer.parseInt(chunk);
        Log.i("KK",""+cs);
        long start = (cs-1)*chunksize;
        Log.i("KK",""+start);
        byte[] chunkdata = FileDecollate(start, chunksize, file);
        if (chunkdata == null) {
            return;
        }
        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder multipart = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        multipart.addFormDataPart("id", id);
        multipart.addFormDataPart("name", name);
        multipart.addFormDataPart("size", String.valueOf(size));
        multipart.addFormDataPart("chunks", chunks);
        multipart.addFormDataPart("chunk", chunk);
        multipart.addFormDataPart("type", "video/mp4");
        multipart.addFormDataPart("vname", vname);
        multipart.addFormDataPart("vtype", "10086");
        multipart.addFormDataPart("vtext", vtext);
        multipart.addFormDataPart("vtag", vtag);
        multipart.addFormDataPart("file", filename, RequestBody.create(chunkdata));
        multipart.addFormDataPart("usid", usid);
        multipart.addFormDataPart("uname", uname);
        multipart.addFormDataPart("filesize", String.valueOf(size));
        ProgressResponseBody responseBody = new ProgressResponseBody(multipart.build(), new ProgressResponseListener() {
            @Override
            public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
                Log.i("KKKK", "---------");
                Log.i("KKKK", bytesRead + "---------");
                Log.i("KKKK", contentLength + "---------");
                if(bytesRead >= contentLength)
                {
                    Log.i("KKKK", "---------"+ "上传完成"+ "---------");
                    if (listener != null)
                    {
                        listener.Progress(bytesRead);
                    }
                }

            }
        });
        Request request = new Request.Builder()
                .url(url+"/us/upload")
                .post(responseBody)
                .build();
        client.newCall(request).execute();

    }

    @Override
    public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
    }
    //外部调用接口
    public interface  ProgressListener{
        void Progress(long byteCount);
    }
    private ProgressListener listener;
    public void setOnProgressListener(ProgressListener listener)
    {
        this.listener = listener;
    }
}
